from rest_framework import mixins, viewsets
from api.models import Order ,OrderDetail
from api.serializers import OrderSerializer ,OrderDetailSerializer, OrderSerializerList
from api.filters import OrderFilter ,BrandOrderDetails
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter, SearchFilter
from api.utils.OrderResponse import SuccessResponse
from api.utils.Pageination import AppNumberPagination

class OrderViewSet(
    mixins.CreateModelMixin,  # 添加创建功能
    mixins.RetrieveModelMixin,  # 添加单个查询功能
    mixins.UpdateModelMixin,  # 添加更新功能
    mixins.ListModelMixin,  # 添加列表查询功能
    mixins.DestroyModelMixin,  # 添加删除功能
    viewsets.GenericViewSet
):
    queryset = Order.objects.all()
    serializer_class = OrderSerializerList
    filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
    filterset_class = OrderFilter
    search_fields = ['customer']
    ordering_fields = ["order_id"]
    ordering = ('-order_id',)

class OrderViewSetList(
    mixins.CreateModelMixin,  # 添加创建功能
    mixins.RetrieveModelMixin,  # 添加单个查询功能
    mixins.UpdateModelMixin,  # 添加更新功能
    mixins.ListModelMixin,  # 添加列表查询功能
    mixins.DestroyModelMixin,  # 添加删除功能
    viewsets.GenericViewSet
):
    queryset = Order.objects.all()
    serializer_class = OrderSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
    filterset_class = OrderFilter
    pagination_class = AppNumberPagination # 分页功能
    search_fields = ['customer']
    ordering_fields = ["order_id"]
    ordering = ('-order_id',)

    def list(self, request, *args, **kwargs):
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return SuccessResponse(serializer.data,total=queryset.count())
        serializer = self.get_serializer(queryset, many=True)
        return SuccessResponse(serializer.data,total=queryset.count())


class OrderDetailViewSet(
    mixins.CreateModelMixin,  # 添加创建功能
    mixins.RetrieveModelMixin,  # 添加单个查询功能
    mixins.UpdateModelMixin,  # 添加更新功能
    mixins.ListModelMixin,  # 添加列表查询功能
    mixins.DestroyModelMixin,  # 添加删除功能
    viewsets.GenericViewSet
):
    queryset = OrderDetail.objects.all()
    serializer_class = OrderDetailSerializer
    filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter]
    filterset_class = BrandOrderDetails
    search_fields = ['customer']
    ordering_fields = ["order_id"]
    ordering = ('-order_id',)
